<?php
namespace app\admin\controller\house;

use app\admin\controller\Common;
use app\admin\model\HouseProperty as PropertyModel;
use app\admin\validate\HouseProperty as PropertyValidate;

class Property extends Common
{
    public function index()
    {
        $loginUser = $this->auth->getLoginUser();
        $property = PropertyModel::where('admin_user_id', $loginUser['id'])
        ->order('sort')
        ->paginate(10);
        $this->assign('property', $property);
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        $data = ['name' => '', 'address' => ''];
        if ($id) {
            if (!$data = PropertyModel::get($id)) {
                $this->error('记录不存在');
            }
        }
        $this->assign('data', $data);
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function save()
    {
        $id = $this->request->post('id/d', 0);
        $loginUser = $this->auth->getLoginUser();
        $data = [
            'admin_user_id' => $loginUser['id'],
            'name' => $this->request->post('name/s', '', 'trim'),
            'address' => $this->request->post('address/s', '', 'trim'),
            'sort' => $this->request->post('sort/d', 0),
        ];
        $validate = new PropertyValidate();
        if ($id) {
            if (!$validate->check($data)) {
                $this->error('修改失败,' . $validate->getError() . '。');
            }
            if (!$role = PropertyModel::get($id)) {
                $this->error('修改失败，记录不存在。');
            }
            $role->save($data);
            $this->success('修改成功。');
        }
        if (!$validate->check($data)) {
            $this->error('添加失败，' . $validate->getError() . '。');
        }
        PropertyModel::create($data);
        $this->success('添加成功。');
    }

    public function delete()
    {
        $id = $this->request->param('id/d', 0);
        $validate = new PropertyValidate();
        if (!$validate->scene('delete')->check(['id' => $id])) {
            $this->error('删除失败，' . $validate->getError() . '。');
        }
        if (!$user = PropertyModel::get($id)) {
            $this->error('删除失败，记录不存在。');
        }
        $user->delete();
        $this->success('删除成功。');
    }

    public function sort()
    {
        $sort = $this->request->post('sort/a', []);
        $data = [];
        foreach ($sort as $k => $v) {
            $data[] = ['id' => (int)$k, 'sort' => (int)$v];
        }
        $property = new PropertyModel;
        $property->saveAll($data);
        $this->success('改变排序成功');
    }
}
